<template>
  <div class="rank-page">
    <div class="sort">
      <el-radio-group v-model="sort" @change="handleChange">
        <el-radio-button label="tokenId">tokenId</el-radio-button>
        <el-radio-button label="score">score</el-radio-button>
        <el-radio-button label="step">step</el-radio-button>
      </el-radio-group>
    </div>
    <el-table :data="tableData" stripe v-loading="loading" style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="player" label="Player" width="200px">
        <template #default="scope">
          <el-link type="primary" :href="`https://rinkeby.etherscan.io/address/${scope.row.player}`" target="_blank">
            {{ scope.row.address }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="tokenId" label="TokenId" align="center">
        <template #default="scope">
          <el-link type="primary"
            :href="`https://rinkeby.etherscan.io/token/${gameContract}?a=${scope.row.tokenId}#inventory`"
            target="_blank">
            {{ scope.row.tokenId }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="score" sortable label="Score" />
      <el-table-column prop="step" sortable label="Step" />
      <el-table-column prop="duration" sortable label="Duration" />
      <el-table-column prop="startTime" label="Start" width="180" />
      <el-table-column prop="endTime" label="End" width="180" />
      <el-table-column prop="" label="Action">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleDetail(scope.row)">Detail</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="NFT Detail" width="800px" :before-close="handleClose">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="Contract">
          <el-link type="primary" :href="`https://rinkeby.etherscan.io/address/${gameContract}`" target="_blank">
            {{gameContract}}
          </el-link>
        </el-descriptions-item>
        <el-descriptions-item label="TokenId">
          {{nftDetail.tokenId}}
        </el-descriptions-item>
        <el-descriptions-item label="TokenURI">
          <el-link type="primary" :href="nftDetail.tokenURI" target="_blank">
            {{nftDetail.tokenURI}}
          </el-link>
        </el-descriptions-item>
      </el-descriptions>
      <div class="img" v-loading="loadingImg" element-loading-text="Loading metadata...">
        <el-image style="width: 100%; height: 100%;" :src="imgUrl" fit="cover" :preview-src-list="[imgUrl]" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { graphql } from '@/api'
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { useEthersStore } from '@/stores/modules/providers'
import axios from 'axios'
import defaultImg from '@/assets/1650712244230.jpg'
const { gameContract } = useEthersStore()
const tableData = ref([])
const loading = ref(false)
const sort = ref('tokenId')

async function handleChange () {
  // tokenId startTime, score, step,  
  const query = `
{
  mintItemEntities(orderBy:${sort.value},orderDirection:desc) {
    id,
    player,
    tokenId,
    score,
    step,
    startTime,
    endTime,
  }
}
`
  try {
    loading.value = true
    const res = await graphql(JSON.stringify({ query }))
    tableData.value = res.mintItemEntities.map(v => {
      v.address = v.player.replace(/^(.{8})(?:\w+)(.{8})$/, '$1******$2')
      v.duration = formatSecond((v.endTime - v.startTime) / 1000)
      v.startTime = dayjs(Number(v.startTime)).format('YYYY-MM-DD HH:mm:ss')
      v.endTime = dayjs(Number(v.endTime)).format('YYYY-MM-DD HH:mm:ss')
      return v
    })
  } catch (error) {
    console.log('[ error ] >', error)
  }
  loading.value = false
}
onMounted(async () => {
  handleChange()
})

function formatSecond (second) {
  const hours = Math.floor((second % 86400) / 3600);
  const minutes = Math.floor(((second % 86400) % 3600) / 60);
  const seconds = Math.floor(((second % 86400) % 3600) % 60);
  if (hours > 0) {
    return `${hours}h ${minutes}m ${seconds}s`
  }
  if (minutes > 0) {
    return `${minutes}m ${seconds}s`
  }
  if (seconds > 0) {
    return `${seconds}s`
  }
}

// dialog
const dialogVisible = ref(false)
const nftDetail = ref({})
const imgUrl = ref(defaultImg)
const loadingImg = ref(false)
async function handleDetail (row) {
  dialogVisible.value = true
  loadingImg.value = true
  const gameContract = useEthersStore().instanceContract()
  try {
    const tokenURI = await gameContract.tokenURI(row.tokenId)
    nftDetail.value = Object.assign({}, row, { tokenURI })

    const res = await axios.get(tokenURI)
    if (res.status === 200) {
      imgUrl.value = res.data.image.replace(
        'ipfs://',
        'https://ipfs.io/ipfs/'
      )
    }

  } catch (error) {
    console.log('[ error ] >', error)
  }

  loadingImg.value = false
}
function handleClose () {
  dialogVisible.value = false
  imgUrl.value = defaultImg
}

</script>

<style lang="less" scoped>
.rank-page {
  max-width: 1200px;
  margin: 0 auto;
  padding-top: 20px;
  overflow: hidden;
  .sort {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }
}
.img {
  margin: 15px auto 0;
  width: 200px;
  height: 200px;
}
</style>